package com.zhongge.singlelistOJ;

/**
 * @ClassName Partition
 * @Description TODO 分割链表
 * @Author 笨忠
 * @Date 2025/8/9 17:59
 * @Version 1.0
 */
class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}

public class Partition {
    public static ListNode partition(ListNode pHead, int x) {
        //cur指针
        ListNode cur = pHead;
        //辅助链表
        ListNode aStart = null;
        ListNode aEnd = null;
        ListNode bStart = null;
        ListNode bEnd = null;
        //遍历原链表
        while (cur != null) {
            if (cur.val < x) {
                if (aStart == null) {
                    aStart = aEnd = cur;
                }else {
                    //尾插进入a
                    //绑后
                    aEnd.next = cur;
                    //尾变新
                    aEnd = aEnd.next;
                }
            } else {
               //尾插进入b
                if (bStart == null) {
                    bStart = bEnd = cur;
                }else {
                    //尾插进入a
                    //绑后
                    bEnd.next = cur;
                    //尾变新
                    bEnd = bEnd.next;
                }
            }
            cur = cur.next;
        }
        if (aEnd == null) {
            return bStart;
        }
        if (bStart != null) {
            bEnd.next = null;
        }
        aEnd.next = bStart;

        return aStart;
    }

    public static void main(String[] args) {
       /* ListNode node1 = new ListNode(34);
        ListNode node2 = new ListNode(89);
        ListNode node3 = new ListNode(23);
        ListNode node4 = new ListNode(13);
        ListNode node5 = new ListNode(34);
        ListNode node6 = new ListNode(54);*/


        /*node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
*/
        ListNode node1 = new ListNode(3);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(3);
        node1.next = node2;
        node2.next = node3;

        ListNode prev = node1;
        while (prev != null) {
            System.out.print(prev.val + " ");
            prev = prev.next;
        }
        System.out.println();
        System.out.println("=================");
        ListNode listNode = partition(node1, 4);
        ListNode cur = listNode;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
    }
}
